import { Component, OnInit, ViewChild } from '@angular/core';
import { FarmService } from "../../../service/farm.service";
import { Farm } from "../../../entity/farm.model";
import { TagData } from "../../../entity/tag-data.model";
import { DataSourceService } from "../../../service/data-source/data-source.service";
import { DatePipe } from "@angular/common";
import { List } from 'linqts';
import { ApplicationService } from "../../../service/application.service";
import { NzMessageService } from 'ng-zorro-antd';
import { WindSpeedDistributionComponent } from "../../monitor/wind-energy/wind-speed-distribution/wind-speed-distribution.component";
import { WindDirectionComponent } from "../../monitor/wind-energy/wind-direction/wind-direction.component";
import { InterceptorService } from '../../../service/interceptor/interceptor-service';

@Component({
  selector: 'app-wind-resource',
  templateUrl: './wind-resource.component.html',
  styleUrls: ['./wind-resource.component.css']
})
export class WindResourceComponent implements OnInit {
  //时间选择
  date = new Date();
  startDate: Date = new Date(this.date.getFullYear(), 0, 1);
  endDate: Date = new Date(this.date.getFullYear() + 1, 0, 1);
  /**
   *数据间隔时间
   *
   * @memberof WindResourceComponent
   */
  interval = 1800;
  /**
   *年的数组
   *
   * @type {number[]}
   * @memberof WindResourceComponent
   */
  public years: number[] = []
  /**
   *当前年份
   *
   * @type {number}
   * @memberof WindResourceComponent
   */
  public currentYear: number = this.date.getFullYear();
  /**
   *12个月
   *
   * @type {number[]}
   * @memberof WindResourceComponent
   */
  public months: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  /**
   *当前月份
   *
   * @type {number}
   * @memberof WindResourceComponent
   */
  public currentMonth: number = this.months[this.date.getMonth()];
  /**
   *测点数据
   *
   * @type {CodeData[][]}
   * @memberof WindResourceComponent
   */
  tagDataSeries: CodeData[][];
  /**
   *风场公司切换
   *
   * @type {number}
   * @memberof WindResourceComponent
   */
  active: number = 0;
  /**
   *年度月份切换
   *
   * @type {number}
   * @memberof WindResourceComponent
   */
  tabNum: number = 1;
  farms: Farm[];
  month: number = 1;
  farmDatas: FarmWindData[];
  bladesindiameter: number = 82;
  totalFarmData: FarmWindData = {
    speedData: [],
    direcData: [],
    windData: [],
  };
  codes: string[];
  @ViewChild(WindSpeedDistributionComponent)
  speedDistribution: WindSpeedDistributionComponent;
  @ViewChild(WindDirectionComponent)
  windDirection: WindDirectionComponent;
  constructor(
    private farmService: FarmService,
    public application: ApplicationService,
    private dataSource: DataSourceService,
    private datePipe: DatePipe,
    private http: InterceptorService,
  ) { }

  ngOnInit() {
    let currentYear = this.currentYear;
    for (let i = 0; i < 10; i++) {
      this.years.push(currentYear--)
    };
    this.speedDistribution.seriesData = [];
    this.windDirection.seriesData = [];
    this.windDirection.windEnergySeriesData = [];
    this.getTime();
    this.initData();
  }
  initData() {
    const farms = this.application.currentUserFarms.filter(farm => farm.farmCategory === 'winfarm');
    const items = farms.map(o => o.farmId);
    this.farmService.getFarmSweptDiameterByFarmId(items)
      .then(res => {

        for (let t in res) {
          let i = farms.findIndex(o => o.farmId == parseInt(t));
          if (i > -1) {
            let num = this.bladesindiameter;
            if (res[t]) {
              num = res[t]['bladeSindiaMeter'] ? res[t]['bladeSindiaMeter'] : this.bladesindiameter;
            }
            farms[i].windEnergy = Math.pow(num / 2, 2) * Math.PI;
          }
        }
        this.farms = [...farms];
        this.createFarmsModel();

      })
      .catch(err => {
        console.log(err);
      });
  }
  createFarmsModel() {
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    const MeanWindSpeed = this.application.tagDict['CWindSpeed'], // 预测风速
      AmbWindDir = this.application.tagDict['CAmbWindDir']; // 预测风向
    this.farmDatas = [];
    let farmDatas: FarmWindData[] = [];
    let tagDataSeries: CodeData[][] = [];
    const companyCode = this.application.currentCompany.companyCode,
      AmbWindDirCode = this.dataSource.buildTagCode([companyCode, '4'], AmbWindDir),
      MeanWindSpeedCode = this.dataSource.buildTagCode([companyCode, '4'], MeanWindSpeed);
    let windEnergy = 0;
    this.farms.forEach((farm, i) => {

      let AmbWindDirCode = this.dataSource.buildTagCode([farm.farmCode, '4'], AmbWindDir);
      let MeanWindSpeedCode = this.dataSource.buildTagCode([farm.farmCode, '4'], MeanWindSpeed);

      let farmData: FarmWindData = {
        farmName: farm.farmName,
        farmId: farm.farmId,
        driectionCode: AmbWindDirCode,
        speedCode: MeanWindSpeedCode,
        windEnergy: farm.windEnergy
      };
      windEnergy += farm.windEnergy;
      farmDatas.push(farmData);

    });
    farmDatas.unshift({
      farmName: '公司',
      farmId: 0,
      driectionCode: AmbWindDirCode,
      speedCode: MeanWindSpeedCode,
      windEnergy: windEnergy / this.farms.length //风能平均值
    })
    this.farmDatas = farmDatas;
    let directionMap = {};
    let newDate = new Date();
    ['W', 'WSW', 'SW', 'SSW', 'S', 'SSE', 'SE', 'ESE', 'E', 'ENE', 'NE', 'NNE', 'N', 'NNW', 'NW', 'WNW'].forEach((v, i) => {
      directionMap[v] = 360 / 16 * i;
      tagDataSeries.push([]);
    });
    this.tagDataSeries = tagDataSeries;
    this.getTagData();

  }
  getTagData() {
    this.tagDataSeries.forEach(v => {
      v = [];
    });
    const currentFarmData = this.farmDatas[this.active];
    const codes = [currentFarmData.speedCode, currentFarmData.driectionCode];
    this.dataSource.history
      .getHistories(codes, this.startDate, this.endDate, this.interval)
      .then(res => {
        if (!res) { return false; };

        const driecData = res.filter(o => o.code === currentFarmData.driectionCode && o.value >= 0),
          speedData = res.filter(o => o.code === currentFarmData.speedCode && o.value >= 0),
          codeDatas: CodeData[] = [],
          tagDataSerie: CodeData[][] = [];
        ['W', 'WSW', 'SW', 'SSW', 'S', 'SSE', 'SE', 'ESE', 'E', 'ENE', 'NE', 'NNE', 'N', 'NNW', 'NW', 'WNW'].forEach((v, i) => {
          tagDataSerie.push([]);
        });
        driecData.forEach(data => {
          if (data.value < 0) { return false; };
          const index = speedData.findIndex(o => new Date(o.time).getTime() == new Date(data.time).getTime());

          let obj: CodeData;
          if (index > -1) {
            obj = {
              time: data.time,
              driectionValue: data.value,
              speedValue: speedData[index].value,
              windEnergy: Math.pow(speedData[index].value, 3) * currentFarmData.windEnergy
            };

          } else {
            obj = {
              time: data.time,
              driectionValue: data.value,
              speedValue: 0,
              windEnergy: 0
            };
          }
          codeDatas.push(obj);
          let n = Math.round(data.value / 22.5);
          if (n == 16) n = 0;
          if (n <= 15) {
            this.tagDataSeries[n].push(obj);
            tagDataSerie[n].push(obj);
          }


        });
        //this.farmDatas[this.active].tagData = codeDatas;
        //风场风速汇总
        let data: Data = {};
        for (let i = 0; i < 25; i++) {
          data[i + 1] = 0;
        }
        speedData.forEach((o) => {
          let value = Math.round(o.value);
          if (data[value] || data[value] === 0) {
            data[value] = data[value] + 1;
          } /* else {8
            data[value] = 1;
          } */

        });
        let total = 0;
        // tslint:disable-next-line:forin
        for (const t in data) {
          total += data[t];
        }
        const seriesData: number[][] = [];
        // tslint:disable-next-line:forin
        for (const t in data) {
          seriesData.push([parseFloat(t), data[t] ? parseFloat((data[t] / total * 100).toFixed(2)) : 0]);
        }
        if (this.tabNum) {
          this.farmDatas[this.active].speedData = [...seriesData];
        } else {
          this.farmDatas[this.active].yearSpeedData = [...seriesData];
        };
        // 风场风向风能汇总
        let totalDir = 0,
          totalWindEnergy = 0,
          seriesDatas = [],
          windEnergySeriesData = [];
        tagDataSerie.forEach((v, i) => {
          totalDir += v.length;
          seriesDatas[i] = v.length;
          v.forEach(windEnergy => {
            totalWindEnergy += windEnergy.windEnergy;
          });
          if (v.length) {
            const vData = new List(v),
              sum = vData.Sum(o => o.windEnergy);
            windEnergySeriesData[i] = sum;
          } else {
            windEnergySeriesData[i] = 0;
          }

        });
        if (totalDir) {
          seriesDatas = seriesDatas.map(o => o && parseFloat((o / totalDir * 100).toFixed(2)));

        }
        if (totalWindEnergy) {
          //风能数据
          windEnergySeriesData = windEnergySeriesData.map(o => o && parseFloat((o / totalWindEnergy * 100).toFixed(2)));

        }

        if (this.tabNum) {
          this.farmDatas[this.active].direcData = seriesDatas;
          this.farmDatas[this.active].windData = windEnergySeriesData;
        } else {
          this.farmDatas[this.active].yearDirecData = seriesDatas;
          this.farmDatas[this.active].yearWindData = windEnergySeriesData;
        }
        this.setEcharts();
      });


  }
  onFarmSelect(index: number, farmData?: FarmWindData) {
    this.active = index;
    if (this.tabNum) {
      if (this.farmDatas[this.active]['speedData']) {
        this.setEcharts();
      } else {
        this.getTagData();
      }
    } else {
      if (this.farmDatas[this.active]['yearSpeedData']) {
        this.setEcharts();
      } else {
        this.getTagData();
      }
    }
  }
  setEcharts() {
    if (this.tabNum) {
      this.speedDistribution.seriesData = this.farmDatas[this.active].speedData;
      this.windDirection.seriesData = this.farmDatas[this.active].direcData;
      this.windDirection.windEnergySeriesData = this.farmDatas[this.active].windData;

    } else {
      this.speedDistribution.seriesData = this.farmDatas[this.active].yearSpeedData;
      this.windDirection.seriesData = this.farmDatas[this.active].yearDirecData;
      this.windDirection.windEnergySeriesData = this.farmDatas[this.active].yearWindData;
    }
    this.speedDistribution.initEcharts();
    this.windDirection.initEcharts();
    this.windDirection.initEchartsWindEnergy();
  }
  onSearch() {
    this.farmDatas.forEach(farmData => {
      farmData.windData = null;
      farmData.direcData = null;
      farmData.speedData = null;
      farmData.yearWindData = null;
      farmData.yearDirecData = null;
      farmData.yearSpeedData = null;
    });
    this.getTime();
    this.getTagData();
  }
  onChangeYear(ev) {
    this.currentYear = ev;
  }
  onChangeMonth(ev) {
    this.currentMonth = ev;
  }
  onClickHeader(n: number) {
    this.tabNum = n;
    this.getTime();
    if (this.tabNum) {
      if (this.farmDatas[this.active]['speedData']) {
        this.setEcharts();
      } else {
        this.getTagData();
      }
    } else {
      if (this.farmDatas[this.active]['yearSpeedData']) {
        this.setEcharts();
      } else {
        this.getTagData();
      }
    }

  }
  getTime() {
    if (this.tabNum) {
      this.interval = 1800;
      this.startDate = new Date(this.currentYear, this.currentMonth - 1, 1);
      this.endDate = new Date(this.currentYear, this.currentMonth, 1);
    } else {
      //this.interval = 1800;
      this.startDate = new Date(this.currentYear, 0, 1);
      this.endDate = new Date(this.currentYear + 1, 0, 1);
      if (this.endDate.getTime() - this.startDate.getTime() < 1000 * 60 * 60 * 24 * 15) {
        this.interval = 1800;
      } else {
        this.interval = 3600 * 3;
      }
    }
  }
}
interface FarmWindData {
  farmName?: string;
  farmId?: number;
  driectionCode?: string;
  speedCode?: string;
  //tagData?: CodeData[];
  windEnergy?: number;
  speedData?: any[];
  direcData?: any[];
  windData?: any[];
  yearSpeedData?: any[];
  yearDirecData?: any[];
  yearWindData?: any[];

}
interface CodeData {
  time: Date,
  driectionValue: number,
  speedValue?: number,
  windEnergy?: number,
}
interface Data {
  [index: number]: number
}



// WEBPACK FOOTER //
// ./src/app/module/data-analysis/wind-resource/wind-resource.component.ts